//
//  WebArticleViewController.swift
//  miaoyin
//
//  Created by David on 2017/2/21.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class WebArticleViewController: UIViewController, UIWebViewDelegate {

    var webURL: URL?
    
    var aid: String?
    
    var aTitle: String?
    
    convenience init(title: String, url: URL, id: String?){
        self.init()
        aTitle = title
        self.title = title
        webURL = url
        aid = id
    }
    
    var webView: UIWebView!
    var progressBar: UIProgressView!
    //    var toolbar: UIToolbar!
    var backToolbar: UIToolbar!
    
    var bottomBar: UIVisualEffectView!
    
    var likeBtn: UIButton!
    var remarkBtn: UIButton!
    var shareBtn: UIButton!
    
    var shareObj: FCSharingObj?
    var shareView: FCSharingView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        webView = UIWebView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
        webView.delegate = self
        webView.scalesPageToFit = true
        
        webView.scrollView.contentInset.bottom += 44
        
        view.addSubview(webView)
        
        progressBar = UIProgressView(frame: CGRect(x: 0, y: 64, width: view.bounds.width, height: 0))
        view.addSubview(progressBar)
        progressBar.tintColor = themeColor1
        
        //        toolbar = UIToolbar(frame: CGRect(x: 0, y: view.frame.height - 44, width: view.frame.width, height: 44))
        //        view.addSubview(toolbar)
        //        var toolbarItems:[UIBarButtonItem] = []
        //        toolbarItems.append(UIBarButtonItem(barButtonSystemItem: .Undo, target: self, action: ""))
        //        toolbarItems.append(UIBarButtonItem(barButtonSystemItem: .Redo, target: self, action: ""))
        //        toolbarItems.append(UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: ""))
        //
        //        toolbar.setItems(toolbarItems, animated: true)
        
        //        backToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 128, height: 44))
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "navbar_back"), style: .plain, target: self, action: #selector(WebArticleViewController.backBtnClicked))
        
        bottomBar = UIVisualEffectView(frame: CGRect(x: 0, y: view.frame.height-44, width: view.frame.width, height: 44))
        bottomBar.effect = UIBlurEffect(style: .extraLight)
        view.addSubview(bottomBar)
        
//        likeBtn = UIButton(frame: CGRect(x: 16, y: 12, width: 80, height: 20))
//        likeBtn.setImage(#imageLiteral(resourceName: "like"), for: .normal)
//        likeBtn.imageView?.contentMode = .scaleAspectFit
//        likeBtn.setTitle("0", for: .normal)
//        likeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        likeBtn.setTitleColor(UIColor.gray, for: .normal)
//        bottomBar.addSubview(likeBtn)
        
        remarkBtn = UIButton(frame: CGRect(x: 8, y: 12, width: 88, height: 20))
        remarkBtn.setImage(#imageLiteral(resourceName: "remark"), for: .normal)
        remarkBtn.imageView?.contentMode = .scaleAspectFit
        remarkBtn.setTitle("0", for: .normal)
        remarkBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        remarkBtn.setTitleColor(UIColor.gray, for: .normal)
        bottomBar.addSubview(remarkBtn)
        remarkBtn.addTarget(self, action: #selector(WebArticleViewController.remarkBtnClick), for: .touchUpInside)
        
        shareBtn = UIButton(frame: CGRect(x: view.frame.width - 44, y: 12, width: 20, height: 20))
        shareBtn.setImage(#imageLiteral(resourceName: "share"), for: .normal)
        shareBtn.imageView?.contentMode = .scaleAspectFit
        bottomBar.addSubview(shareBtn)
        shareBtn.addTarget(self, action: #selector(WebArticleViewController.shareBtnClick), for: .touchUpInside)
        
        if webURL != nil{
            webView.loadRequest(URLRequest(url: webURL!))
        }
        if aid != nil{
            print("aid:\(aid ?? "")")
            ChangyanSDK.getCommentCount(nil, topicSourceID: aid!, topicUrl: "", complete: { (code, str) in
                if str != nil{
                    print(str!)
                    do{
                        let jsonObj = try JSONSerialization.jsonObject(with: str!.data(using: .utf8)!, options: .allowFragments) as? NSDictionary
                        let jsonRes = jsonObj?.object(forKey: "result") as? NSDictionary
                        let jsonData = jsonRes?.object(forKey: self.aid!) as? NSDictionary
                        let commentNum = jsonData?.object(forKey: "comments") as? Int
                        
                        if commentNum != nil{
                            if commentNum! < 1000 {
                                self.remarkBtn.setTitle("\(commentNum!)", for: .normal)
                            }else{
                                self.remarkBtn.setTitle("999+", for: .normal)
                            }
                            
                        }
                        
                    }catch let err{
                        print(err)
                    }
                }
            })
        }
        
        shareView = FCSharingView(frame: view.frame)
        view.addSubview(shareView)
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.interactivePopGestureRecognizer?.delegate = nil
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        progressBar.alpha = 1
        progressBar.setProgress(0.1, animated: true)
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        progressBar.setProgress(0.9, animated: true)
        UIView.animate(withDuration: 0.3) { 
            self.progressBar.alpha = 0
        }
        
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        //        progressBar.progress = 1
        //        progressBar.alpha = 0
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func backBtnClicked(){
        
        if webView.canGoBack{
            webView.goBack()
            var backBtnItems:[UIBarButtonItem] = []
            backBtnItems.append(UIBarButtonItem(image: UIImage(named: "navbar_back"), style: .plain, target: self, action: #selector(WebArticleViewController.backBtnClicked)))
            backBtnItems.append(UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(WebArticleViewController.closeBtnClicked)))
            navigationItem.leftBarButtonItems = backBtnItems
        }else{
             _ = navigationController?.popViewController(animated: true)
        }
        
        
    }
    
    func closeBtnClicked(){
        _ = navigationController?.popViewController(animated: true)
    }
    
    func likeBtnClick(){
        
    }
    
    func remarkBtnClick(){
        if aid != nil{
            let remarkVC = ChangyanSDK.getListCommentViewController("", topicID: nil, topicSourceID: aid!, categoryID: nil, topicTitle: aTitle ?? "") as? UIViewController
            if remarkVC != nil {
//                hidesBottomBarWhenPushed = true
//                navigationController?.pushViewController(remarkVC!, animated: true)
                
                let nav = RemarkBlackViewController(rootViewController: remarkVC!)
                present(nav, animated: true, completion: nil)
            }
            
        }
        
    }
    
    func shareBtnClick(){
        shareView.openView(shareObj: shareObj)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

class RemarkBlackViewController: UINavigationController {
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
}
